#ifndef DUMMYDIALOG_H
#define DUMMYDIALOG_H

#include "resource2.h"
#include "FindWindows.h"

class DialogThread
{
	class MyDialog : public CDialogImpl<MyDialog>
	{
	public:
		enum { IDD = IDD_DUMMY };
	private:
		BEGIN_MSG_MAP(MyDialog)
			REFLECT_NOTIFICATIONS()
		END_MSG_MAP()
	} m_md;
	HWND m_dlg;

public:
	DialogThread() : m_dlg(NULL) {}
	~DialogThread()
	{
		if (m_dlg != NULL)
			::EndDialog(m_dlg, 0);

		/* N.B.:  EndDialog does not block when destroying the HWND (per MSDN).  So there's a race-condition here.  
		   It's minor, only shows up in DEBUG, but the CWindowImplRoot dtor ASSERTs that its hwnd is not NULL yet, 
		   about 1 time in 10.  So I'll poll just a bit.
		*/
		while (m_md.m_hWnd != NULL)
		{
			::Sleep(1);
		}
	}
	
	HWND StartDialog()
	{
		HANDLE h = ::CreateThread(NULL, 0, ThreadProc, this, 0, NULL);
		if (h != NULL)
			::CloseHandle(h);

		// wait a sec for window to come up
		TitlePredicate tp(L"DummyDialog");
		VisiblePredicate vp;
		ProcessPredicate pp(::GetCurrentProcessId());
		DialogPredicate dp;

		for(int i=0; i<1000; ++i)
		{
			m_dlg = ::FindDesiredWindow(vp, dp, pp, tp);
			if (m_dlg)
				break;
			Sleep(1);
		}
		return m_dlg;
	}
private:
	static DWORD WINAPI ThreadProc(LPVOID lp)
	{
		return (reinterpret_cast<DialogThread*>(lp))->ThreadProc();
	}
	DWORD ThreadProc()
	{
		m_md.DoModal();
		return 0;
	}
};

#endif
